package io.argin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.argin.entity.Dept;
import io.argin.entity.Emp;
import io.argin.service.IDeptService;
import io.argin.service.IEmpService;
import io.argin.util.MapUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author argin
 * @since 2020-12-25
 */
@RestController
public class EmpController {

    @Resource
    private IEmpService empService;

    @Resource
    private IDeptService deptService;

    @GetMapping("/listD")
    public List<Dept> listDepts() {
        return deptService.list();
    }

    @PostMapping("/insert")
    public String insertEmp(@RequestBody Emp emp) {
        System.out.println("provider:insert");
        System.out.println("emp = " + emp);
        empService.save(emp);
        return "redirect:/list";
    }

    @PostMapping("/map/insert")
    public void insertMap(@RequestBody Map<String, Object> map){
        empService.save(MapUtils.parseEmp(map));
    }

    @GetMapping("/delete/{id}")
    public String deleteEmp(@PathVariable Integer id) {
        System.out.println("provider:delete");
        System.out.println("id = " + id);
        empService.removeById(id);
        return "redirect:/list";
    }

    @GetMapping("/get/{id}")
    public Emp getEmp(@PathVariable Integer id) {
        return empService.getById(id);
    }

    @GetMapping("/get")
    Emp getEmpById(@RequestParam Integer id) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return empService.getById(id);
    }

    @PostMapping("/update")
    public String updateEmp(@RequestBody Emp emp) {
        System.out.println("provider:update");
        System.out.println("emp = " + emp);
        empService.updateById(emp);
        return "redirect:/list";
    }

    @GetMapping("/list")
    public List<Emp> listEmps() {
        return empService.list();
    }

    @GetMapping("/list/{name}")
    public List<Emp> listEmpsByName(@PathVariable String name) {
        name = name == null || name.equals("") ? "%" : name;
        QueryWrapper<Emp> wrapper = new QueryWrapper<>();
        wrapper.like("name", name);
        return empService.list(wrapper);
    }


}
